import { Parser } from 'json2csv'
import FileSaver from 'file-saver'
import JsPDF from 'jspdf'
import { uniqBy } from 'lodash'
import { font } from './font/fs_gb2312'
const pageSizeList = {
  "A0": [762, 1194],      
  "A1": [595, 940],      
  "A2": [441, 787],      
  "A3": [297, 441],      
  "A4": [210, 297],      
  "A5": [148, 210],      
  "A6": [114, 148],      
  "A7": [79, 114],      
  "A8": [53, 79],        
  "A9": [36, 53],        
  "B0": [1016, 1536],      
  "B1": [791, 1189],      
  "B2": [582, 964],      
  "B3": [416, 635],      
  "B4": [295, 416],      
  "B5": [197, 295],      
  "Archa": [686, 1092],     
  "Archb": [582, 964],     
  "Archc": [441, 787],     
  "Archd": [372, 619],     
  "Arche": [297, 441],     
  "Flsa": [762, 1194],     
  "HalfLetter": [762, 1194],    
  "Letter": [762, 1194],    
  "Legal": [792, 1189],    
  "Ledger": [1572, 2328],
  "Note": [610, 889],
  "Letter11x17": [825, 1106]       
}


function isNumericWithPercentageAndDot(str) {
  var regex = /^[0-9.%]+$/;
  return regex.test(str);
}
export const exportPdf = (dataList, fieldsList, {pageOrientation,pageSize}={pageOrientation:'Portrait',pageSize:'A4'}) => {
  const dataListClone = JSON.parse(JSON.stringify(dataList))
  let fieldsListClone = JSON.parse(JSON.stringify(fieldsList))
  const doc = new JsPDF({  
    unit: 'mm',  
    format: pageSizeList[pageSize],  
    orientation: pageOrientation.toLowerCase()
  });
  doc.addFileToVFS('fs_gb2312-normal.ttf', font);
  doc.addFont('fs_gb2312-normal.ttf', 'fs_gb2312', 'normal');
  doc.setFont("fs_gb2312");
  try {
    let arr = uniqBy(fieldsListClone.filter(i => i.dataType === 'dimension'), 'bind')
    if (arr.length > 1) {
      let arr2 = fieldsListClone.filter(i => i.dataType !== 'dimension')
      fieldsListClone = arr.concat(arr2)
    }
    fieldsListClone = uniqBy(fieldsListClone,'bind')
  } catch (error) {

  }
  const data = dataListClone.map(item => {
    Object.keys(item).map(key => {
      let findKey = fieldsListClone.find(i => i.bind === key  &&  i.dataType === 'dimension')
      if(findKey) {
        item[findKey.alias] = item[key]
      }
      if (typeof item[key] === 'string' && item[key].startsWith('<a') && item[key].endsWith('</a>')) {
        item[key] = item[key].replace(new RegExp('<[^<>]+>','g'),"")
      }
    })
    return item
  })
  let columns = fieldsListClone.map(i => ({ header: i.alias , dataKey: i.alias }))
  doc.autoTable({
    columns,
    body: data,
    horizontalPageBreak: true,
    styles: { overflow: 'ellipsize', cellWidth: 'wrap',font: 'fs_gb2312',fontStyle: 'normal'},
    columnStyles: { text: { cellWidth: 'auto' } }
  })
  doc.save('Export.pdf')
}

export const exportCvs = (dataList, fieldsList) => {  
  const dataListClone = JSON.parse(JSON.stringify(dataList))
  let fieldsListClone = JSON.parse(JSON.stringify(fieldsList))
  try {
    let arr = uniqBy(fieldsListClone.filter(i => i.dataType === 'dimension'), 'bind')
    if (arr.length > 1) {
      let arr2 = fieldsListClone.filter(i => i.dataType !== 'dimension')
      fieldsListClone = arr.concat(arr2)
    }
    fieldsListClone = uniqBy(fieldsListClone,'bind')
  } catch (error) {

  }
  const data = dataListClone.map(item => {
      Object.keys(item).map(key => {      
      let findKey = fieldsListClone.find(i => i.bind === key  &&  i.dataType === 'dimension')
      if(findKey) {
        item[findKey.alias] = item[key]
      }
      if (typeof item[key] === 'string' && item[key].startsWith('<a') && item[key].endsWith('</a>')) {
        item[key] = HYPERLINK(item[key])
      }else if ((typeof item[key] === 'string'||typeof item[key] === 'number') && isNumericWithPercentageAndDot(item[key])) {
        item[key] = item[key]+'\t'
      }
    })
    return item
  })
  const fields = fieldsListClone.map(item => {
    return {
      label: item.alias,
      value: item.alias
    }
  })
  const opts = {
    fields
  }
  const json2csvParser = new Parser(opts)
  const csv = json2csvParser.parse(data)
  let blob = new Blob(['\uFEFF' + csv], {
    type: 'text/plaincharset=utf-8'
  })
  FileSaver(blob, 'Export.csv')
}
export const exportFilterRuleCvs = (dataList, fieldsList) => {
  const dataListClone = JSON.parse(JSON.stringify(dataList))
  let fieldsListClone = JSON.parse(JSON.stringify(fieldsList))
  const fields = fieldsListClone.map(item => {
    return {
      label: item.alias,
      value: item.field
    }
  })
  const opts = {
    fields
  }
  const json2csvParser = new Parser(opts)
  const csv = json2csvParser.parse(dataListClone)
  let blob = new Blob(['\uFEFF' + csv], {
    type: 'text/plaincharset=utf-8'
  })
  FileSaver(blob, 'Export.csv')
}
export const exportExcel = (dataList, fieldsList) => {
  const dataListClone = JSON.parse(JSON.stringify(dataList))
  let fieldsListClone = JSON.parse(JSON.stringify(fieldsList))
  try {
    let arr = uniqBy(fieldsListClone.filter(i => i.dataType === 'dimension'), 'bind')
    if (arr.length > 1) {
      let arr2 = fieldsListClone.filter(i => i.dataType !== 'dimension')
      fieldsListClone = arr.concat(arr2)
    }
    fieldsListClone = uniqBy(fieldsListClone,'bind')
  } catch (error) {

  }
  const data = dataListClone.map(item => {
    Object.keys(item).map(key => {
      let findKey = fieldsListClone.find(i => i.bind === key  &&  i.dataType === 'dimension')
      if(findKey) {
        item[findKey.alias] = item[key]
      }
      if (typeof item[key] === 'string' && item[key].startsWith('<a') && item[key].endsWith('</a>')) {
        item[key] = HYPERLINK(item[key])
      }else if ((typeof item[key] === 'string'||typeof item[key] === 'number') && isNumericWithPercentageAndDot(item[key])) {
        item[key] = item[key]+'\t'
      }
    })
    return item
  })
  const fields = fieldsListClone.map(item => {
    return {
      label: item.alias,
      value: item.alias
    }
  })
  const opts = {
    fields
  }
  const json2csvParser = new Parser(opts)
  const csv = json2csvParser.parse(data)
  let blob = new Blob(['\uFEFF' + csv], {
    type: 'text/plaincharset=utf-8'
  })
  FileSaver(blob, 'Export.xls')
}

function HYPERLINK (html) {
  html = decodeURIComponent(html)
  let placeholder = document.createElement('div')
  placeholder.innerHTML = html
  let nodes = placeholder.childNodes
  const str = `=HYPERLINK("${nodes[0].href}","${nodes[0].text}")`
  placeholder.remove()
  return str
}
